package com.glb.gilibuy.web.admin;

import com.alipay.api.internal.util.StringUtils;
import com.glb.gilibuy.entity.CyclePic;
import com.glb.gilibuy.entity.Product;
import com.glb.gilibuy.entity.ProductCategory;
import com.glb.gilibuy.entity.UserOrder;
import com.glb.gilibuy.util.MapGenerator;
import com.glb.gilibuy.util.SnowflakeIdUtil;
import com.glb.gilibuy.util.UploadUtil;
import com.glb.gilibuy.web.BaseController;
import com.glb.gilibuy.web.vo.ProductCategoryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yupeng Zhang
 * @Date: 2021-08-09 11:30
 */
@Api(tags = "管理员商品模块")
@Controller
public class AdminProductController extends BaseController {
    @ApiOperation(value = "添加商品", notes = "添加商品", produces = "application/json")
    @PostMapping("/admin/addProduct")
    @ResponseBody
    public Map<String, Object> addProduct(@RequestParam("productName") String productName,
                                          //分类名字ming'zi和id可同时提交，id优先，会覆盖名字的提交结果；都不交返回错误
                                          @RequestParam(value = "productCategory", required = false) String productCategory,
                                          @RequestParam(value = "productCategoryId", required = false) String categoryId,
                                          @RequestParam("productPrice") BigDecimal productPrice,
                                          @RequestParam(value = "productIntro", required = false) String productIntro,
                                          @RequestParam(value = "productHeat", required = false) BigDecimal productHeat,
                                          @RequestParam(value = "productSequence", defaultValue = "500") Integer productSequence,
                                          @RequestParam(value = "productAmount", defaultValue = "0") Integer productAmount,
                                          @RequestParam("coverPic") MultipartFile coverPic,
                                          @RequestParam(value = "pics", required = false) List<MultipartFile> pics,
                                          @RequestParam(value = "size", required = false) String size,
                                          @RequestParam(value = "weight", required = false) String weight,
                                          @RequestParam(value = "isVirtual", defaultValue = "false") boolean isVirtual) {
        //输入分类名字转化成分类id
        String productCategoryId = null;
        if (!StringUtils.isEmpty(productCategory)) {
            //检查输入
            //检查输入的商品类型
            for (ProductCategoryVO categoryVO : productCategoryService.selectAllCategories()) {
                //如果有子类
                if (!categoryVO.getChildList().isEmpty()) {
                    for (ProductCategoryVO categoryVO1 : categoryVO.getChildList()) {
                        //如果有子类
                        if (!categoryVO1.getChildList().isEmpty()) {
                            for (ProductCategoryVO categoryVO2 : categoryVO1.getChildList()) {
                                if (categoryVO2.getProductCategoryName().equals(productCategory)) {
                                    productCategoryId = categoryVO2.getProductCategoryId();
                                }
                            }
                        }
                        if (categoryVO1.getProductCategoryName().equals(productCategory)) {
                            productCategoryId = categoryVO1.getProductCategoryId();
                        }
                    }
                }
                if (categoryVO.getProductCategoryName().equals(productCategory)) {
                    productCategoryId = categoryVO.getProductCategoryId();
                }
            }
            if (productCategoryId == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
        }

        if (!StringUtils.isEmpty(categoryId)) {
            ProductCategory productCategory1 = productCategoryService.selectCategoryByCategoryId(categoryId);
            if (productCategory1 == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
            productCategoryId = categoryId;
        }

        if (productCategoryId == null) {
            return MapGenerator.getRes(500, "请输入商品分类名称或分类id！");
        }

        //coverPic理论上不能为空
        String coverPicURL = "";
        if (coverPic != null) {
            Map<String, Object> coverPicRes = UploadUtil.uploadFile(coverPic);
            if (coverPicRes.get("status").equals(200)) {
                coverPicURL = String.valueOf(coverPicRes.get("data"));
            } else {
                return coverPicRes;
            }
        }

        //pics可以为空
        String picsURL = null;
        if (!pics.isEmpty()) {
            List<String> picsURLList = null;
            Map<String, Object> picsRes = UploadUtil.uploadFiles(pics);
            if (picsRes.get("status").equals(200)) {
                picsURLList = (List<String>) picsRes.get("data");
            } else {
                return picsRes;
            }
            picsURL = UploadUtil.listToString(picsURLList);
        }

        //设置内容
        Product product = new Product();
        product.setProductName(productName);
        product.setProductCategoryId(productCategoryId);
        product.setProductPrice(productPrice);
        product.setProductIntro(productIntro);
        product.setProductHeat(productHeat);
        product.setProductSequence(productSequence);
        product.setProductAmount(productAmount);
        product.setCoverPic(coverPicURL);
        product.setPics(picsURL);
        product.setSize(size);
        product.setWeight(weight);
        //默认销量为0
        product.setSaleCount(0);
        if (isVirtual) {
            product.setIsVirtual(1);
        } else {
            product.setIsVirtual(0);
        }
        //生成id
        product.setProductId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        //激活
        product.setIsDeleted(0);
        //生成日期
        product.setGmtCreate(new Date());

        //添加商品
        if (productService.addProduct(product) > 0) {
            return MapGenerator.getRes(200, "添加商品成功！");
        }
        return MapGenerator.getRes(500, "添加商品失败！");
    }

    @ApiOperation(value = "获取商品分类", notes = "获取商品分类", produces = "application/json")
    @GetMapping("/admin/categoryList")
    @ResponseBody
    public Map<String, Object> getCategories() {
        List<ProductCategoryVO> productCategoryVOList = productCategoryService.selectAllCategories();
        if (!productCategoryVOList.isEmpty()) {
            return MapGenerator.getResWithData(200, "获取商品分类列表成功！", productCategoryVOList);
        } else {
            return MapGenerator.getRes(200, "获取结果为空！");
        }
    }

    @ApiOperation(value = "获取商品列表", notes = "获取商品列表", produces = "application/json")
    @PostMapping("/admin/productList")
    @ResponseBody
    public Map<String, Object> getProductList() {
        List<Product> productList = productService.findAllProduct();
        if (!productList.isEmpty()) {
            Map<String, Object> data = new HashMap<>();
            data.put("productList", productList);
            return MapGenerator.getResWithData(200, "获取结果为空！", data);
        } else {
            return MapGenerator.getRes(500, "获取商品分类列表失败！");
        }
    }

    @ApiOperation(value = "添加商品分类", notes = "添加商品分类", produces = "application/json")
    @PostMapping("/admin/addCategory")
    @ResponseBody
    public Map<String, Object> addCategory(@RequestParam("categoryName") String categoryName,
                                           //父分类名字和id可同时提交，id优先，会覆盖名字的提交结果；都不交父分类为0
                                           @RequestParam(value = "parentName", required = false) String parentName,
                                           @RequestParam(value = "parentId", required = false) String parentId,
                                           @RequestParam(value = "categorySequence", defaultValue = "500") Integer categorySequence) {
        //输入分类名字转化成分类id
        String parentCategoryId = null;
        if (!StringUtils.isEmpty(parentName)) {
            //检查输入
            //检查输入的商品类型
            for (ProductCategoryVO categoryVO : productCategoryService.selectAllCategories()) {
                //如果有子类
                if (!categoryVO.getChildList().isEmpty()) {
                    for (ProductCategoryVO categoryVO1 : categoryVO.getChildList()) {
                        //如果有子类
                        if (!categoryVO1.getChildList().isEmpty()) {
                            for (ProductCategoryVO categoryVO2 : categoryVO1.getChildList()) {
                                if (categoryVO2.getProductCategoryName().equals(parentName)) {
                                    parentCategoryId = categoryVO2.getProductCategoryId();
                                }
                            }
                        }
                        if (categoryVO1.getProductCategoryName().equals(parentName)) {
                            parentCategoryId = categoryVO1.getProductCategoryId();
                        }
                    }
                }
                if (categoryVO.getProductCategoryName().equals(parentName)) {
                    parentCategoryId = categoryVO.getProductCategoryId();
                }
            }
            if (parentCategoryId == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
        }

        if (!StringUtils.isEmpty(parentId)) {
            ProductCategory productCategory1 = productCategoryService.selectCategoryByCategoryId(parentId);
            if (productCategory1 == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
            parentCategoryId = parentId;
        }

        if (parentCategoryId == null) {
            parentCategoryId = "0";
        }

        ProductCategory productCategory = new ProductCategory();
        productCategory.setProductCategoryName(categoryName);
        productCategory.setProductCategorySequence(categorySequence);
        productCategory.setParentCategoryId(parentCategoryId);

        productCategory.setProductCategoryId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        productCategory.setIsDeleted(0);
        productCategory.setGmtCreate(new Date());

        //添加商品
        if (productCategoryService.addCategory(productCategory) > 0) {
            return MapGenerator.getRes(200, "添加商品分类成功！");
        }
        return MapGenerator.getRes(500, "添加商品分类失败！");
    }

    @ApiOperation(value = "添加轮播图", notes = "添加轮播图", produces = "application/json")
    @PostMapping("/admin/addCyclePic")
    @ResponseBody
    public Map<String, Object> addCyclePic(@RequestParam("cyclePic") MultipartFile cyclePic,
                                           //商品id和url可同时提交，url优先，会覆盖商品id的提交结果；都不交返回错误
                                           @RequestParam(value = "productId", required = false) String productId,
                                           @RequestParam(value = "url", required = false) String url,
                                           @RequestParam(value = "cyclePicSequence", defaultValue = "500") Integer cyclePicSequence) {
        //输入分类名字转化成分类id
        String jumpLink = null;
        if (!StringUtils.isEmpty(productId)) {
            Product productFromDB = productService.selectProductByProductId(productId);
            if (productFromDB == null) {
                return MapGenerator.getRes(500, "不存在该商品！");
            }
            jumpLink = "/detailPage?productId=" + productId;
        }

        if (!StringUtils.isEmpty(url)) {
            jumpLink = url;
        }

        if (jumpLink == null) {
            return MapGenerator.getRes(500, "请输入商品id或自定义虚拟路径！");
        }

        //cyclePic理论上不能为空
        String cyclePicURL = "";
        if (cyclePic != null) {
            Map<String, Object> cyclePicRes = UploadUtil.uploadFile(cyclePic);
            if (cyclePicRes.get("status").equals(200)) {
                cyclePicURL = String.valueOf(cyclePicRes.get("data"));
            } else {
                return cyclePicRes;
            }
        }

        CyclePic cyclePic1 = new CyclePic();
        cyclePic1.setCyclePic(cyclePicURL);
        cyclePic1.setCyclePicSequence(cyclePicSequence);
        cyclePic1.setJumpLink(jumpLink);
        cyclePic1.setCyclePicId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        cyclePic1.setIsDeleted(0);
        cyclePic1.setGmtCreate(new Date());

        //添加商品
        if (cyclePicService.addCyclePic(cyclePic1) > 0) {
            return MapGenerator.getRes(200, "添加轮播图成功！");
        }
        return MapGenerator.getRes(500, "添加轮播图失败！");
    }

    @ApiOperation(value = "修改商品信息", notes = "修改商品信息(除了文件，不修改的信息原样填回，不填也没事)", produces = "application/json")
    @PostMapping("/admin/updateProduct")
    @ResponseBody
    public Map<String, Object> updateProduct(@RequestParam("productId") String productId,
                                             @RequestParam(value = "productName", required = false) String productName,
                                             //分类名字和id可同时提交，id优先，会覆盖名字的提交结果；都不交返回错误
                                             @RequestParam(value = "productCategory", required = false) String productCategory,
                                             @RequestParam(value = "productCategoryId", required = false) String categoryId,
                                             @RequestParam(value = "productPrice", required = false) BigDecimal productPrice,
                                             @RequestParam(value = "productIntro", required = false) String productIntro,
                                             @RequestParam(value = "productHeat", required = false) BigDecimal productHeat,
                                             @RequestParam(value = "productSequence", defaultValue = "500") Integer productSequence,
                                             @RequestParam(value = "productAmount", defaultValue = "0") Integer productAmount,
                                             @RequestParam(value = "coverPic", required = false) MultipartFile coverPic,
                                             @RequestParam(value = "coverPicURL", required = false) String oldCoverPicURL,
                                             @RequestParam(value = "pics", required = false) List<MultipartFile> pics,
                                             @RequestParam(value = "picsURL", required = false) String oldPicsURL,
                                             @RequestParam(value = "size", required = false) String size,
                                             @RequestParam(value = "weight", required = false) String weight,
                                             @RequestParam(value = "isVirtual", defaultValue = "false") boolean isVirtual,
                                             @RequestParam(value = "isDeleted", defaultValue = "false") boolean isDeleted) {
        Product productFromDB = productService.selectProductByProductId(productId);
        if (productFromDB == null) {
            return MapGenerator.getRes(500, "不存在该商品！");
        }

        //输入分类名字转化成分类id
        String productCategoryId = null;
        if (!StringUtils.isEmpty(productCategory)) {
            //检查输入
            //检查输入的商品类型
            for (ProductCategoryVO categoryVO : productCategoryService.selectAllCategories()) {
                //如果有子类
                if (!categoryVO.getChildList().isEmpty()) {
                    for (ProductCategoryVO categoryVO1 : categoryVO.getChildList()) {
                        //如果有子类
                        if (!categoryVO1.getChildList().isEmpty()) {
                            for (ProductCategoryVO categoryVO2 : categoryVO1.getChildList()) {
                                if (categoryVO2.getProductCategoryName().equals(productCategory)) {
                                    productCategoryId = categoryVO2.getProductCategoryId();
                                }
                            }
                        }
                        if (categoryVO1.getProductCategoryName().equals(productCategory)) {
                            productCategoryId = categoryVO1.getProductCategoryId();
                        }
                    }
                }
                if (categoryVO.getProductCategoryName().equals(productCategory)) {
                    productCategoryId = categoryVO.getProductCategoryId();
                }
            }
            if (productCategoryId == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
        }

        if (!StringUtils.isEmpty(categoryId)) {
            ProductCategory productCategory1 = productCategoryService.selectCategoryByCategoryId(categoryId);
            if (productCategory1 == null) {
                return MapGenerator.getRes(500, "不存在该商品分类！");
            }
            productCategoryId = categoryId;
        }

        if (coverPic != null) {
            Map<String, Object> coverPicRes = UploadUtil.uploadFile(coverPic);
            if (coverPicRes.get("status").equals(200)) {
                oldCoverPicURL = String.valueOf(coverPicRes.get("data"));
            } else {
                return coverPicRes;
            }
        }

        if (!pics.isEmpty()) {
            List<String> picsURLList = null;
            Map<String, Object> picsRes = UploadUtil.uploadFiles(pics);
            if (picsRes.get("status").equals(200)) {
                picsURLList = (List<String>) picsRes.get("data");
            } else {
                return picsRes;
            }
            oldPicsURL = UploadUtil.listToString(picsURLList);
        }

        if (!StringUtils.isEmpty(productName)) {
            productFromDB.setProductName(productName);
        }
        if (!StringUtils.isEmpty(productCategoryId)) {
            productFromDB.setProductCategoryId(productCategoryId);
        }
        if (productPrice != null) {
            productFromDB.setProductPrice(productPrice);
        }
        if (!StringUtils.isEmpty(productIntro)) {
            productFromDB.setProductIntro(productIntro);
        }
        if (productHeat != null) {
            productFromDB.setProductHeat(productHeat);
        }
        if (productSequence != null) {
            productFromDB.setProductSequence(productSequence);
        }
        if (productAmount != null) {
            productFromDB.setProductAmount(productAmount);
        }
        if (!StringUtils.isEmpty(oldCoverPicURL)) {
            productFromDB.setCoverPic(oldCoverPicURL);
        }
        if (!StringUtils.isEmpty(oldPicsURL)) {
            productFromDB.setPics(oldPicsURL);
        }
        if (!StringUtils.isEmpty(size)) {
            productFromDB.setSize(size);
        }
        if (!StringUtils.isEmpty(weight)) {
            productFromDB.setWeight(weight);
        }
        if (isVirtual) {
            productFromDB.setIsVirtual(1);
        } else {
            productFromDB.setIsVirtual(0);
        }
        if (isDeleted) {
            productFromDB.setIsDeleted(1);
        } else {
            productFromDB.setIsDeleted(0);
        }

        //更新商品
        if (productService.updateProduct(productFromDB) > 0) {
            return MapGenerator.getRes(200, "修改商品成功！");
        }
        return MapGenerator.getRes(500, "修改商品失败！");
    }

}
